import { LEANCLOUD_CONFIG } from '../config/leancloud.js';

// Record类字段定义
export const RECORD_FIELDS = {
  USER_ID: 'userId',
  TITLE: 'title',
  MESSAGES: 'messages',
  IS_ACTIVE: 'isActive',
  CREATED_AT: 'createdAt',
  UPDATED_AT: 'updatedAt',
  LAST_MESSAGE_TIME: 'lastMessageTime'
};

// Record API封装类
class RecordAPI {
  constructor() {
    this.baseURL = LEANCLOUD_CONFIG.serverURL;
    this.appId = LEANCLOUD_CONFIG.appId;
    this.appKey = LEANCLOUD_CONFIG.appKey;
    this.className = 'Record';
  }

  // 获取请求头
  getHeaders() {
    return {
      'Content-Type': 'application/json',
      'X-LC-Id': this.appId,
      'X-LC-Key': this.appKey
    };
  }

  // 构建URL
  buildURL(endpoint) {
    return `${this.baseURL}/1.1${endpoint}`;
  }

  // 处理响应
  async handleResponse(response) {
    const data = await response.json();
    
    if (!response.ok) {
      throw new Error(data.error || `HTTP error! status: ${response.status}`);
    }
    
    return data;
  }

  // 获取用户的所有对话记录
  async getRecordsByUser(userId) {
    try {
      const response = await fetch(
        this.buildURL(`/classes/Record?where=${encodeURIComponent(JSON.stringify({
          [RECORD_FIELDS.USER_ID]: userId,
          [RECORD_FIELDS.IS_ACTIVE]: true
        }))}&order=-${RECORD_FIELDS.LAST_MESSAGE_TIME}`),
        {
          method: 'GET',
          headers: this.getHeaders()
        }
      );

      const data = await this.handleResponse(response);
      
      return {
        success: true,
        data: data.results.map(record => ({
          id: record.objectId,
          title: record[RECORD_FIELDS.TITLE],
          messages: record[RECORD_FIELDS.MESSAGES] || [],
          createdAt: record[RECORD_FIELDS.CREATED_AT],
          updatedAt: record[RECORD_FIELDS.UPDATED_AT],
          lastMessageTime: record[RECORD_FIELDS.LAST_MESSAGE_TIME]
        }))
      };
    } catch (error) {
      console.error('获取对话记录失败:', error);
      return {
        success: false,
        error: this.getErrorMessage(error.message)
      };
    }
  }

  // 创建新对话记录
  async createRecord(userId, title = '新对话') {
    try {
      const response = await fetch(this.buildURL('/classes/Record'), {
        method: 'POST',
        headers: this.getHeaders(),
        body: JSON.stringify({
          [RECORD_FIELDS.USER_ID]: userId,
          [RECORD_FIELDS.TITLE]: title,
          [RECORD_FIELDS.MESSAGES]: [],
          [RECORD_FIELDS.IS_ACTIVE]: true,
          [RECORD_FIELDS.LAST_MESSAGE_TIME]: {
            __type: 'Date',
            iso: new Date().toISOString()
          }
        })
      });

      const data = await this.handleResponse(response);
      
      return {
        success: true,
        data: {
          id: data.objectId,
          title: title,
          messages: [],
          createdAt: data.createdAt,
          updatedAt: data.updatedAt,
          lastMessageTime: data[RECORD_FIELDS.LAST_MESSAGE_TIME]
        }
      };
    } catch (error) {
      console.error('创建对话记录失败:', error);
      return {
        success: false,
        error: this.getErrorMessage(error.message)
      };
    }
  }

  // 获取特定对话记录的详情
  async getRecordDetail(recordId) {
    try {
      const response = await fetch(this.buildURL(`/classes/Record/${recordId}`), {
        method: 'GET',
        headers: this.getHeaders()
      });

      const data = await this.handleResponse(response);
      
      return {
        success: true,
        data: {
          id: data.objectId,
          title: data[RECORD_FIELDS.TITLE],
          messages: data[RECORD_FIELDS.MESSAGES] || [],
          createdAt: data[RECORD_FIELDS.CREATED_AT],
          updatedAt: data[RECORD_FIELDS.UPDATED_AT],
          lastMessageTime: data[RECORD_FIELDS.LAST_MESSAGE_TIME]
        }
      };
    } catch (error) {
      console.error('获取对话详情失败:', error);
      return {
        success: false,
        error: this.getErrorMessage(error.message)
      };
    }
  }

  // 更新对话记录（添加消息）
  async updateRecord(recordId, updateData) {
    try {
      const response = await fetch(this.buildURL(`/classes/Record/${recordId}`), {
        method: 'PUT',
        headers: this.getHeaders(),
        body: JSON.stringify({
          ...updateData,
          [RECORD_FIELDS.UPDATED_AT]: {
            __type: 'Date',
            iso: new Date().toISOString()
          },
          [RECORD_FIELDS.LAST_MESSAGE_TIME]: {
            __type: 'Date',
            iso: new Date().toISOString()
          }
        })
      });

      const data = await this.handleResponse(response);
      
      return {
        success: true,
        data: {
          id: data.objectId,
          updatedAt: data.updatedAt
        }
      };
    } catch (error) {
      console.error('更新对话记录失败:', error);
      return {
        success: false,
        error: this.getErrorMessage(error.message)
      };
    }
  }

  // 添加消息到对话记录
  async addMessage(recordId, message) {
    try {
      // 先获取当前记录
      const recordResult = await this.getRecordDetail(recordId);
      if (!recordResult.success) {
        return recordResult;
      }

      const currentMessages = recordResult.data.messages;
      const newMessages = [...currentMessages, message];

      // 更新记录
      return await this.updateRecord(recordId, {
        [RECORD_FIELDS.MESSAGES]: newMessages
      });
    } catch (error) {
      console.error('添加消息失败:', error);
      return {
        success: false,
        error: this.getErrorMessage(error.message)
      };
    }
  }

  // 更新对话标题
  async updateRecordTitle(recordId, title) {
    try {
      return await this.updateRecord(recordId, {
        [RECORD_FIELDS.TITLE]: title
      });
    } catch (error) {
      console.error('更新对话标题失败:', error);
      return {
        success: false,
        error: this.getErrorMessage(error.message)
      };
    }
  }

  // 删除对话记录（软删除）
  async deleteRecord(recordId) {
    try {
      const response = await fetch(this.buildURL(`/classes/Record/${recordId}`), {
        method: 'PUT',
        headers: this.getHeaders(),
        body: JSON.stringify({
          [RECORD_FIELDS.IS_ACTIVE]: false,
          [RECORD_FIELDS.UPDATED_AT]: {
            __type: 'Date',
            iso: new Date().toISOString()
          }
        })
      });

      const data = await this.handleResponse(response);
      
      return {
        success: true,
        data: {
          id: data.objectId,
          updatedAt: data.updatedAt
        }
      };
    } catch (error) {
      console.error('删除对话记录失败:', error);
      return {
        success: false,
        error: this.getErrorMessage(error.message)
      };
    }
  }

  // 错误消息处理
  getErrorMessage(errorMessage) {
    if (errorMessage.includes('network') || errorMessage.includes('fetch')) {
      return '网络连接失败，请检查网络设置';
    } else if (errorMessage.includes('401')) {
      return '认证失败，请检查应用配置';
    } else if (errorMessage.includes('404')) {
      return '请求的资源不存在';
    } else {
      return '操作失败，请稍后重试';
    }
  }
}

// 创建单例实例
const recordAPI = new RecordAPI();

export default recordAPI;
